<?php

namespace app\uni\controller;

use think\Controller;


//引入微信SDK
use EasyWeChat\Factory;

class Business extends Controller
{
    public function __construct()
    {   
        //继承父类
        parent::__construct();

        $this->BusinessModel = model('Business.Business');
        $this->ProductModel = model('Order.Product');   

        //AppID(小程序ID)	wx2a856458dd72f8fc
        //APPSecret(密钥)   32853da6085786edfdb034f3524efecd
        //全局配置微信的SDK
        $config = [
            'app_id' => 'wx2a856458dd72f8fc',
            'secret' => '32853da6085786edfdb034f3524efecd',
            'response_type' => 'array',     //调用SDK接口返回数据类型(可定义返回类型，此处为数组)

            //debug 日志
            'log' => [
                'level' => 'debug',
                'file'  => __DIR__.'wechat.log',
            ],
        ];

        //得到一个小程序SDK的实例对象
        $this->app = Factory::miniProgram($config);
    }

    //授权登录的方法
    public function login()
    {
        if($this->request->isPost())
        {
            //获取临时凭证
            $code = $this->request->param('code','','trim');

            if(empty($code))
            {   
                $this->error('获取临时凭证失败!');
                exit;
            }

            //$app->auth->session(string $code)
            //此处$app在全局使用了$this->app来替代
            //请求微信公众平台 根据jsCode获取用户session信息
            $wxauth = $this->app->auth->session($code);

            //获取openid
            $openid = isset($wxauth['openid']) ? trim($wxauth['openid']) : '';

            if(empty($openid))
            {
                $this->error('授权失败！');
                exit;
            }
            
            //去business表中查找 openid绑定的用户记录
            $business = $this->BusinessModel->where(['openid' => $openid])->find();

            if($business)
            {   
                //有绑定过账号
                $this->success('授权登录成功',null,$business);
                exit;
            }else
            {
                //没有绑定的账号
                $this->success('授权成功，请绑定账号',null,['action' => 'bind','openid'=>$openid]);
                exit; 
            }   
        }
    }

    //绑定账号
    public function bind()
    {
        if($this->request->isAjax())
        {
            $mobile = $this->request->param('mobile','','trim');
            $password = $this->request->param('password','','trim');
            $openid  = $this->request->param('openid','','trim');

            //手机号判空
            if(empty($mobile))
            {
                $this->error('手机号码不能为空!');
                exit;
            }
            //密码判空
            if(empty($password))
            {
                $this->error('密码不能为空!');
                exit;
            }
            //openid判空
            if(empty($openid))
            {
                $this->error('openid不能为空!');
                exit;
            }

            //数据库查询对应用户信息
            $business = $this->BusinessModel->where(['mobile' => $mobile])->find();

            if($business)
            {
                //若能查出来对应用户，则说明用户已注册过账号，只需要执行将openid更新到该用户信息中即可
                //update 更新语句 openid
                $result = $this->BusinessModel->where(['id' => $business['id']])->update(['openid' => $openid]);

                if($result === FALSE)
                {
                    $this->error('绑定账号失败');
                    exit;
                }

                //查询一遍最新的数据
                $business = $this->BusinessModel->find($business['id']);

                //再将最新数据$business传回去
                $this->success('绑定账号成功', null, $business);
                exit;
            }else
            {
                //没有查出来对应用户，则说明用户还未注册过账号
                //此时需要将用户进行账号注册，并将openid也插入到该新用户的信息中

                //生成密码盐
                $salt = randstr();

                //加密密码
                $password = md5($password.$salt);

                //组装数据
                $data = [
                    'openid' => $openid,
                    'mobile' => $mobile,
                    'nickname' => build_encrypt($mobile,3,4,'*'), //脱敏显示
                    'password' => $password,
                    'salt' => $salt,
                    'gender' => '0', //性别
                    'deal' => '0',  //成交状态
                    'money' => '0', //余额
                    'auth' => '0',  //邮箱认证
                ];

                 //查询出防伪查询的渠道来源的ID信息 数据库查询
                 $data['sourceid'] = model('common/Business/Source')->where(['name'=>['LIKE', "%防伪查询%"]])->value('id');

                 //执行插入 返回自增的条数
                 $result = $this->BusinessModel->validate('common/Business/Business')->save($data);

                 if($result === FALSE)
                 {
                    //失败
                    $this->error($this->BusinessModel->getError());
                    exit;
                 }else
                 {
                    //查询出当前插入的数据记录
                    $business = $this->BusinessModel->find($this->BusinessModel->id);

                    //注册
                    $this->success('注册成功',null,$business);
                    exit;
                 }
            }
        }
    }

    //解除账号绑定
    public function unbind()
    {
        if($this->request->isPost())
        {
             $busid = $this->request->param('busid',0,'trim');

             //查看用户是否存在
             $business = $this->BusinessModel->find($busid);

             if(!$business)
             {
                $this->error('用户不存在');
                exit;
             }

             //解除绑定
             //解除绑定的逻辑即是将对应用户的"openid"字段设置为null
             $result = $this->BusinessModel->where(['id' => $busid])->update(['openid' => NULL]);

             if($result == FALSE)
             {
                $this->error('解除绑定失败');
                exit;
             }else
             {
                $this->success('解除账号绑定成功');
                exit;
             }
        }
    }

    //H5端和APP-PLUS端
    public function web()
    {
        if($this->request->isPost())
        {
            $mobile = $this->request->param('mobile','','trim');
            $password = $this->request->param('password','','trim');

            //到数据库中寻找对应用户
            $business = $this->BusinessModel->where(['mobile' => $mobile])->find();

            if($business)
            {
                //若成功查到用户,验证其密码是否正确
                $repass = md5($password.$business['salt']);

                //密码不正确
                if($business['password'] != $repass)
                {
                    $this->error('密码不正确');
                    exit;
                }

                $this->success('登录成功',null,$business);
                exit;
            }else
            {
                //若查询用户失败，即说明是新用户
                //新用户执行注册功能,将数据插入到数据库中

                //生成一个密码盐
                $salt = randstr();

                //加密密码
                $password = md5($password.$salt);

                //组装数据
                $data = [
                    'mobile' => $mobile,
                    'nickname' => build_encrypt($mobile, 3, 4, '*'), //脱敏显示
                    'password' => $password,
                    'salt' => $salt,
                    'gender' => '0', //性别
                    'deal' => '0', //成交状态
                    'money' => '0', //余额
                    'auth' => '0', //邮箱认证
                ];

                //查询出防伪查询的渠道来源的ID信息 数据库查询
                $data['sourceid'] = model('common/Business/Source')->where(['name' => ['LIKE','%防伪查询%']]->value('id'));

                //执行插入 返回自增的条数
                $result = $this->BusinessModel->validate('common/Business/Business')->save($data);

                if($result == FALSE)
                {
                    //失败
                    $this->error($this->BusinessModel->getError());
                    exit;
                }else
                {
                    //查询出当前插入的数据记录
                    $business = $this->BusienssModel->find($this->BusinessModel->id);

                    //注册
                    $this->success('注册成功',null,$business);
                    exit;
                }
            }
        }
    }
     //返回用户的订单商品
     public function product()
     {
         if($this->request->isPost())
         {
             $busid = $this->request->param('busid', 0, 'trim');
             $page = $this->request->param('page', 1, 'trim');
             $limit = $this->request->param('limit', 5, 'trim');
             $keyword = $this->request->param('keyword', '', 'trim');
             $offset = ($page-1)*$limit;
 
             $where = ['busid' => $busid];
 
             if(!empty($keyword))
             {
                 $where['products.name'] = ['LIKE', "%$keyword%"];
             }
 
             $list = $this->ProductModel
                 ->with(['products'])
                 ->where($where)
                 ->limit($offset, $limit)
                 ->select();
 
             if($list)
             {
                 $this->success('返回列表', null, $list);
                 exit;
             }else
             {
                 $this->error('暂无数据');
                 exit;
             }
         }
     }

    //查询验证真假的方法
    public function validator()
    {
        if($this->request->isPost())
        {
            $code = $this->request->param('code', 0, 'trim');

            $result = $this->ProductModel->with(['products'])->where(['query_code' => $code])->find();

            if($result === FALSE)
            {
                $this->error('未查询到防伪码数据'); 
                exit;
            }

            //更新一下查询的次数
            $query_num = isset($result['query_num']) ? trim($result['query_num']) : 1;
            $query_num++;

            //更新
            $this->ProductModel->where(['id' => $result['id']])->update(['query_num' => $query_num]) && $result['query_num'] = $query_num;

            $this->success('查询防伪码成功', null, $result);
            exit;
        }
    }

    // 生成小程序码
    public function generate()
    {
        if($this->request->isPost())
        {
            $code = $this->request->param('code', 0, 'trim');

            $product = $this->ProductModel->with(['products'])->where(['query_code' => $code])->find();

            if(!$product)
            {
                $this->error('防伪码产品不存在');
                exit;
            }

            //调用EasyWechat实例对象(小程序) 来生成小程序码
            $path = "/pages/validate/info?code=$code";

            //返回生成小程序码的一个文件的二进制流
            $response = $this->app->app_code->get($path);

            $data = [
                'id' => $product['id']
            ];

            // 保存小程序码到文件
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse)
            {   
                //如果获取文件流成功，则保存
                $filename = $response->saveAs('./uploads/wxcode', "$code.png");

                if($filename) $data['query_qrcode'] = "/uploads/wxcode/$filename";
            }
            
            //更新数据
            $result = $this->ProductModel->isUpdate(true)->save($data);


            //失败情况
            if($result === FALSE)
            {
                $this->error('更换防伪码失败');
                exit;
            }

            //查询一次最新的数据
            $product = $this->ProductModel->with(['products'])->where(['query_code' => $code])->find();

            //将最新数据返回
            $this->success('更换防伪码成功', null, $product);
            exit;
        }
    }

}
